import { record, pack } from 'rrweb';
import { RrwebEventType } from './enum';
import { v4 as uuidv4 } from 'uuid';
import ErrorStackParser from 'error-stack-parser';
import { useRrwebInfo } from '@/stores/rrwebInfo';

const recorderPlugin = {
  install(app, options = {}) {
    const { setRrwebInfo } = useRrwebInfo();
    // 创建Web Worker
    const worker = new Worker(new URL('./logWorker.js', import.meta.url), {
      type: 'module',
    });

    let stopRecord = null;
    let lastFullSnapshotTime = 0;
    const FULL_SNAPSHOT_INTERVAL = 10_000; // 每10秒全量快照

    let latestMeta = {};
    let latestFullSnapshot = {};

    const startRecord = () => {
      if (stopRecord) return;

      worker.postMessage({ type: 'INIT' });

      stopRecord = record({
        emit(event) {
          if (event.type === 4) {
            latestMeta = {
              ...event,
              timestamp: Date.now(),
            };
            return;
          }

          // 性能优化：增量事件直接发送，全量快照节流
          if (
            event.type === RrwebEventType.IncrementalSnapshot ||
            (event.type === RrwebEventType.FullSnapshot &&
              Date.now() - lastFullSnapshotTime > FULL_SNAPSHOT_INTERVAL)
          ) {
            worker.postMessage({
              type: 'ADD_EVENT',
              event: {
                ...event,
                timestamp: Date.now(), // 添加精确时间戳
              },
            });

            if (event.type === RrwebEventType.FullSnapshot) {
              lastFullSnapshotTime = Date.now();
              latestFullSnapshot = {
                ...event,
                timestamp: Date.now(),
              };
            }
          }
        },
        recordCanvas: true,
        collectFonts: true,
        checkoutEveryNms: 10 * 1000,
        sampling: {
          mousemove: 100, // 鼠标移动事件的采样间隔（毫秒）
          mouseInteraction: true, // 是否记录鼠标交互事件（点击、滚动等）
          scroll: 100, // 滚动事件的采样间隔（毫秒）
        },
      });
    };

    startRecord();

    // 手动触发完整快照
    const triggerFullSnapshot = () => {
      if (!stopRecord) return;
      stopRecord.takeFullSnapshot();
    };

    // 停止录制
    const stopBehaviorRecording = () => {
      if (!stopRecord) return;
      stopRecord();
      stopRecord = null;
      worker.postMessage({ type: 'CLEAR' });
    };

    const handleFullRrwebData = (events) => {
      const fullEvents = events.find(
        (item) => item.type === RrwebEventType.FullSnapshot
      );
      if (!fullEvents) {
        return [latestFullSnapshot, ...events];
      }
      return events;
    };

    // 错误捕获处理
    async function captureErrorWithContext(errorData) {
      return new Promise((resolve) => {
        const requestId = uuidv4();

        // 防止webwork不响应
        const timeoutId = setTimeout(() => {
          worker.removeEventListener('message', handleEvents);
          resolve({ ...errorData, events: null });
        }, 2500); // 短于requestIdleCallback的timeout

        const handleEvents = ({ data }) => {
          if (data.type === 'EVENTS_RESPONSE' && data.requestId === requestId) {
            clearTimeout(timeoutId);
            worker.removeEventListener('message', handleEvents);
            resolve({
              ...errorData,
              events: data.events,
            });
          }
          if (data.type === 'memoryStatus') {
            console.log('内存状态:', data.maxMemory);
          }
        };

        worker.addEventListener('message', handleEvents);
        worker.postMessage({ type: 'GET_EVENTS', requestId });
      });
    }

    app.config.errorHandler = async function (err, vm, info) {
      const errorStack = ErrorStackParser.parse(err);

      // 上报错误信息
      const reportData = {
        info,
        position: errorStack[0],
        subType: 'vue',
        type: 'error',
      };
      const data = await captureErrorWithContext(reportData);

      data.events = data.events
        ? [latestMeta, ...handleFullRrwebData(data.events)]
        : [];
      const packedEvents = data.events.map((event) => pack(event));
      setRrwebInfo(packedEvents);
      console.log(packedEvents, 'packedEvents');
    };

    // 监听路由变化
    const handleRouteChange = () => {
      latestMeta = {
        type: 4, // MetaEvent
        data: {
          href: window.location.href,
          width: window.innerWidth,
          height: window.innerHeight,
        },
        timestamp: Date.now(),
      };
      triggerFullSnapshot();
    };

    // 监听所有可能改变 URL 的事件
    // window.addEventListener('popstate', handleRouteChange);
    window.addEventListener('hashchange', handleRouteChange);

    // 在错误监控处使用
    // window.addEventListener('error', async (event) => {
    //   const errorData = {
    //     message: event.message,
    //     stack: event.error?.stack,
    //     component: 'Unknown',
    //     timestamp: new Date().toISOString(),
    //   };

    //   const enrichedData = await captureErrorWithContext(errorData);

    //   window.requestIdleCallback(
    //     () => {
    //       const blob = new Blob([JSON.stringify(enrichedData)], {
    //         type: 'application/json',
    //       });
    //       navigator.sendBeacon('/log-endpoint', blob);
    //     },
    //     { timeout: 3000 }
    //   );
    // });
  },
};

export default recorderPlugin;
